<template>
  <div class="UserPage">
    <div class="page-container">
      <div class="page-header">
        <el-card>
          <div class="page-header-title">
            <div class="user-avatar-container">
              <div class="user-avatar">
                <el-avatar
                    alt="头像"
                    shape="square"
                    :size="100"
                    :src="userInfo.avatarUrl"
                >
                  <img
                      src="https://cube.elemecdn.com/9/c2/f0ee8a3c7c9638a54940382568c9dpng.png"
                      alt="头像"
                  />
                </el-avatar>
              </div>
            </div>
            <div class="words">
            <div class="greeting">
              <div>{{ greeting() }}</div>
              <div>{{ userInfo.nickname }}</div>
            </div>
            <div class="user-tags">
              <el-divider direction="vertical"></el-divider>
              购物车 {{num1}}
              <el-divider direction="vertical"></el-divider>
              浏览 {{num2}}
              <el-divider direction="vertical"></el-divider>
              收藏 {{num3}}
              <el-divider direction="vertical"></el-divider>
              信息 {{num4}}
              <el-divider direction="vertical"></el-divider>
            </div>
            </div>
            <div class="button-group">
              <el-badge :value="200" :max="99">
                <el-button size="small">商店消息</el-button>
              </el-badge>
              <el-badge :is-dot="dot">
              <el-button type="primary" size="small" style="margin-left: 30px" @click="checkTabs3">个人信息</el-button>
              </el-badge>
            </div>
          </div>
        </el-card>
      </div>
    </div>
    <div class="page-content">
      <div class="page-content-container">
        <div class="tabs-region">
      <el-tabs type="border-card" :value="tabs" style="min-height: 800px;">

        <el-tab-pane label="我的收藏" name="1">我的收藏</el-tab-pane>

        <el-tab-pane label="商店消息" name="2">商店消息</el-tab-pane>

        <el-tab-pane label="账号信息" name="3">
          <div class="user-info">
            <el-card shadow="hover">
          <el-descriptions title="个人信息" :column="2">
            <template slot="extra">
              <el-button type="primary" size="small" icon="el-icon-edit" @click="editUserInfo">修改</el-button>
            </template>
            <el-descriptions-item label="用户名">{{userInfo.username}}</el-descriptions-item>
            <el-descriptions-item label="昵称">{{userInfo.nickname}}</el-descriptions-item>
            <el-descriptions-item label="姓名">{{userInfo.name}}</el-descriptions-item>
            <el-descriptions-item label="性别">{{userInfo.gender}}</el-descriptions-item>
            <el-descriptions-item label="电话">{{userInfo.phone}}</el-descriptions-item>
            <el-descriptions-item label="邮箱">{{userInfo.mail}}</el-descriptions-item>
          </el-descriptions>
            </el-card>
          </div>
          <div class="user-address">
            <el-card shadow="hover">
              <div class="address">
              <h4>地址信息</h4>
                <div class="address-button">
                  <el-button type="primary" size="small" icon="el-icon-plus" @click="addAddress">新增</el-button>
                </div>
              </div>
              <template>
                <el-collapse v-model="activeName" accordion>
                  <el-collapse-item
                      v-for="(address, index) in addresses"
                      :key="index"
                      :title="address.label"
                      :name="String(index + 1)"
                  >
                    <div class="address-title">
                      <strong>收货人：{{ address.consignee }}</strong>
                      <el-divider direction="vertical"></el-divider>
                      <strong>性别：{{ address.gender }}</strong>
                      <el-divider direction="vertical"></el-divider>
                      <strong>电话：{{ address.phone }}</strong>
                      <br />
                      <div class="address-button">
                        <el-button type="text" icon="el-icon-edit">修改</el-button>
                        <el-button type="text" icon="el-icon-delete">删除</el-button>
                      </div>
                    </div>
                    <div>所在地区：{{ address.addressInfo }}</div>
                    <div>详细地址：{{ address.detail }}</div>
                  </el-collapse-item>
                </el-collapse>
              </template>
            </el-card>
          </div>
          <div class="user-security">
            <el-card shadow="hover">
              <el-button type="primary">账号设置</el-button>
              <el-button type="info">其它设置</el-button>
            </el-card>
          </div>
        </el-tab-pane>

        <el-tab-pane label="我的订单" name="4">我的订单</el-tab-pane>

        <el-tab-pane label="购物车" name="5">购物车</el-tab-pane>

      </el-tabs>
        </div>
        <div class="card-region">
        <el-card style="min-height: 800px;margin-left: 20px">

        </el-card>
        </div>
      </div>
    </div>

    <el-dialog
        title="修改个人信息"
        :visible.sync="editUserInfoDialog"
        width="30%"
        top="3vh"
    >
      <el-form  :model="editUserForm"
                :rules="addUserRules"
                ref="editUserForm"
                label-width="100px"
                class="editUserForm">
        <el-form-item prop="avatarUrl" label="头像">
          <el-upload
              class="avatar-uploader"
              action=""
              :show-file-list="false"
              :before-upload="beforeAvatarUpload"
              :http-request="uploadEditAvatar"
          >
            <img v-if="editUserForm.avatarUrl" :src="editUserForm.avatarUrl" class="avatar" alt="头像">
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>
        <el-form-item prop="username" label="用户名">
          <el-input
              v-model="editUserForm.username"
              maxlength="16"
              show-word-limit
          ></el-input>
        </el-form-item>
        <el-form-item prop="nickname" label="昵称">
          <el-input
              v-model="editUserForm.nickname"
              maxlength="10"
              show-word-limit>
          </el-input>
        </el-form-item>
        <el-form-item prop="name" label="姓名">
          <el-input
              v-model="editUserForm.name"
              maxlength="16"
              show-word-limit
          ></el-input>
        </el-form-item>
        <el-form-item prop="gender" label="性别">
          <el-radio v-model="editUserForm.gender" label="男">男</el-radio>
          <el-radio v-model="editUserForm.gender" label="女">女</el-radio>
        </el-form-item>
        <el-form-item prop="phone" label="手机号">
          <el-input
              v-model="editUserForm.phone"
              minlength="11"
              maxlength="11"
          ></el-input>
        </el-form-item>
        <el-form-item prop="mail" label="邮箱">
          <el-input
              v-model="editUserForm.mail"
          ></el-input>
        </el-form-item>
        <el-form-item>
          <el-button
              type="primary"
              @click="submitEditUserForm(editUserForm)"
          >提交</el-button
          >
          <el-button @click="resetEditUserForm"
          >重置</el-button
          >
        </el-form-item>
      </el-form>
    </el-dialog>

    <el-dialog
        title="新增地址"
        :visible.sync="addressDialog"
        width="30%"
        top="3vh">
      <el-form  :model="addressForm"
                :rules="addressRules"
                ref="addressForm"
                label-width="100px"
                class="addressForm">
        <el-form-item prop="label" label="地址标签">
          <el-input
            v-model="addressForm.label"
            maxlength="10"
            show-word-limit
            placeholder="请输入地址标签(家，学校，公司...)">
          </el-input>
        </el-form-item>
        <el-form-item prop="consignee" label="收货人">
          <el-input
              v-model="addressForm.consignee"
              maxlength="16"
              show-word-limit
          ></el-input>
        </el-form-item>
        <el-form-item prop="gender" label="性别">
          <el-radio v-model="addressForm.gender" label="男">男</el-radio>
          <el-radio v-model="addressForm.gender" label="女">女</el-radio>
        </el-form-item>
        <el-form-item prop="phone" label="手机号">
          <el-input
              v-model="addressForm.phone"
              minlength="11"
              maxlength="11"
          ></el-input>
        </el-form-item>
        <el-form-item prop="addressCode" label="所在地区">
          <el-cascader
              style="width: 100%"
              :options="regionData"
              v-model="addressForm.addressCode"
              clearable
              >
          </el-cascader>
        </el-form-item>
        <el-form-item prop="detail" label="详细地址">
          <el-input
            v-model="addressForm.detail"
            ></el-input>
        </el-form-item>
        <el-form-item>
          <el-button
            type="primary"
            @click="submitAddressForm"
            >提交</el-button>
          <el-button @click="resetAddressForm"
                     >重置</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>

<script>
import axios from "@/axios/axios";
import { regionData,codeToText} from 'element-china-area-data'

export default {
  data() {
    return {
      activeName: '1',
      editUserInfoDialog:false,
      tabs:"1",
      dot: false,

      num1:0,
      num2:0,
      num3:0,
      num4:0,

      regionData,

      addressDialog:false,
      addressForm:{
        label:"",
        consignee:"",
        gender:"男",
        phone:"",
        addressCode:"",
        addressInfo:"",
        detail:"",
      },
      addresses: [
        {
          id:"",
          label: "",
          consignee: "",
          gender: "",
          phone: "",
          addressInfo:"",
          detail:""
        }
      ],
      options: [{
        value: '家',
        label: '家'
      }, {
        value: '学校',
        label: '学校'
      }, {
        value: '公司',
        label: '公司'
      }],

      userInfo: {
        avatarUrl:"",
        username: "",
        nickname: "",
        name: "",
        gender: "",
        phone: "",
        mail:"",
      },

      editUserForm:{
        avatarUrl:"",
        username:"",
        nickname:"",
        name:"",
        gender:"男",
        phone:"",
        mail:"",
      },

      addUserRules:{
        username: [
          { required: true, message: "请输入用户名", trigger: "blur" },
          {
            min: 6,
            max: 16,
            message: "长度在 6 到 16 个字符",
            trigger: "blur",
          },
          {
            pattern: /^[a-zA-Z0-9]+$/,
            message: "用户名只能包含数字和英文字母(大小写)",
            trigger: "blur",
          }
        ],
        nickname: [
          { required: true, message: "请输入昵称", trigger: "blur" },
          {
            min: 2,
            max: 16,
            message: "长度在 2 到 16 个字符",
            trigger: "blur",
          },
          {
            pattern: /^[\u4e00-\u9fa5a-zA-Z0-9]+$/,
            message: "昵称只能包含中英文和数字",
            trigger: "blur",
          },
        ],
        name: [
            { required: true, message: "请输入姓名", trigger: "blur" },
          {
            min: 2,
            max: 16,
            message: "长度在 2 到 16 个字符",
            trigger: "blur",
          },
          { validator: this.noSpacesValidator, trigger: "blur" }, // 添加自定义验证器
        ],
        phone: [
            { required: true, message: "请输入手机号", trigger: "blur" },
          // 添加正则表达式 pattern: /^1[3|5|7|8|9]\d{9}$/，验证手机号是否正确
          { pattern: /^1[3|5|7|8|9]\d{9}$/, message: '请输入正确的号码格式', trigger: 'blur' }
        ],
        mail: [
            { required: true, message: "请输入邮箱", trigger: "blur" },
          { pattern: /^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+\.[a-zA-Z0-9_-]+$/
            , message: '请输入正确的邮箱格式', trigger: 'blur' }
        ],
      },

      addressRules: {
        label: [
          { required: true, message: "请输入地址标签名", trigger: "blur" },
          {
            min: 1,
            max: 10,
            message: "长度在 2 到 10 个字符",
            trigger: "blur",
          },
          {
            pattern: /^[\u4e00-\u9fa5a-zA-Z0-9]+$/,
            message: "只能包含中英文和数字",
            trigger: "blur",
          },
        ],
        consignee: [
            { required: true, message: "请输入收货人", trigger: "blur" },
          {
            min: 2,
            max: 16,
            message: "长度在 2 到 16 个字符",
            trigger: "blur",
          },
          { validator: this.noSpacesValidator, trigger: "blur" }, // 添加自定义验证器
        ],
        phone: [
          { required: true, message: "请输入手机号", trigger: "blur" },
          // 添加正则表达式 pattern: /^1[3|5|7|8|9]\d{9}$/，验证手机号是否正确
          { pattern: /^1[3|5|7|8|9]\d{9}$/, message: '请输入正确的号码格式', trigger: 'blur' }
        ],
        detail: [
            { required: true, message: "请输入详细地址", trigger: "blur" },
            { validator: this.noSpacesValidator, trigger: "blur" },
        ]
      },
    }
  },



  mounted() {
    this.getUserInfo();
    this.getAddressInfo();
  },

  methods: {
    /**
     * 获取用户信息
     */
    getUserInfo() {
      const params ={
        id : localStorage.getItem("id_supermarket")};
      axios.get("/user/user/info",{params}).then((response) => {
        if (response.data.code === 0) {
          this.$message.error(response.data.msg);
        }else {
          this.userInfo.username = response.data.data.username;
          this.userInfo.nickname = response.data.data.nickname;
          this.userInfo.name = response.data.data.name;
          this.userInfo.gender = response.data.data.gender;
          this.userInfo.phone = response.data.data.phone;
          this.userInfo.mail = response.data.data.mail;
          this.userInfo.avatarUrl = response.data.data.avatarUrl;
          this.checkUserInfo();
        }
      }).catch((error) => {
        console.log(error);
      })
    },

    /**
     * 检测用户信息
     */
    checkUserInfo() {
     if (this.userInfo.name === "" ||
         this.userInfo.gender === "" ||
         this.userInfo.phone === "" ||
         this.userInfo.mail === "" ||
         this.userInfo.name === "暂未填写"||
         this.userInfo.gender === "无"||
         this.userInfo.phone === "暂未填写"||
         this.userInfo.mail === "暂未填写"){
       this.dot= true;
       this.notify();
     }
    },

    /**
     * 发送完善信息通知
     */
    notify() {
      const h = this.$createElement;
      this.$notify({
        title: '个人信息提示',
        message: h('i', { style: 'color: red'}, '请完善个人信息，以便本网站更好的为您提供服务！'),
        type: 'warning',
        duration: 0
      });
    },

    // 计算属性，返回当前的问候语
    greeting() {
      const now = new Date();
      const hours = now.getHours();
      let greetingText;

      if (hours < 8 && hours > 5) {
        greetingText = "早上好！";
      } else if (hours < 12) {
        greetingText = "上午好！";
      } else if (hours < 13) {
        greetingText = "中午好！";
      } else if (hours < 18) {
        greetingText = "下午好！";
      } else {
        greetingText = "晚上好！";
      }

      return greetingText;
    },

    /**
     * 切换至个人信息标签
     */
    checkTabs3(){
      this.tabs = "";
      this.$nextTick(() => {
        this.tabs = "3";
      });
    },

    /**
     * 头像上传
     * @param file
     */
    uploadEditAvatar(file) {
      axios.post("/user/common/upload", file,{headers:{'Content-Type': 'multipart/form-data',}}).then((response) => {
        if(response.data.code===0){
          this.$message.error(response.data.msg);
        }else {
          this.editUserForm.avatarUrl=response.data.data;
          this.$message.success("上传成功");
        }
      }).catch((error) => {
        console.log(error);
      })
    },
    beforeAvatarUpload(file) {
      const isJPG = file.type === "image/jpeg";
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isJPG) {
        this.$message.error("上传头像图片只能是 JPG 格式!");
      }
      if (!isLt2M) {
        this.$message.error("上传头像图片大小不能超过 2MB!");
      }
      return isJPG && isLt2M;
    },

    /**
     * 编辑个人信息
     */
    editUserInfo(){
      this.editUserInfoDialog = true;
      this.getEditUserInfo();
    },

    /*编辑用户信息回显*/
    getEditUserInfo(){
      axios.get("/user/user/editInfo").then((response) => {
        if (response.data.code === 0) {
          this.$message.error(response.data.msg);
        }else {
          this.editUserForm.username = response.data.data.username;
          this.editUserForm.nickname = response.data.data.nickname;
          this.editUserForm.name = response.data.data.name;
          this.editUserForm.gender = response.data.data.gender;
          this.editUserForm.phone = response.data.data.phone;
          this.editUserForm.mail = response.data.data.mail;
          this.editUserForm.avatarUrl = response.data.data.avatarUrl;
        }
      }).catch((error) => {
        console.log(error);
      })
    },

    resetEditUserForm(){
      this.getEditUserInfo();
    },

    submitEditUserForm() {
      if (this.editUserForm.username === this.userInfo.username &&
          this.editUserForm.name === this.userInfo.name &&
          this.editUserForm.avatarUrl === this.userInfo.avatarUrl &&
          this.editUserForm.nickname === this.userInfo.nickname &&
          this.editUserForm.gender === this.userInfo.gender &&
          this.editUserForm.phone === this.userInfo.phone &&
          this.editUserForm.mail === this.userInfo.mail) {
        this.$message.error("信息未修改!");
        return;
      }
      this.$refs.editUserForm.validate((valid) => {
        if (valid) {
          axios.put("/user/user/edit", this.editUserForm).then((response) => {
            if (response.data.code === 0) {
              this.$message.error(response.data.msg);
            } else {
              this.$message.success("修改成功");
              this.editUserInfoDialog = false;
              this.getUserInfo();
            }
          }).catch((error) => {
            console.log(error);
          })
        } else {
          console.log("error submit");
          return false;
        }
      })
    },

    /**
     * 新增地址
     */
    addAddress(){
      this.addressDialog = true;
      this.addressForm.consignee=this.userInfo.name;
      this.addressForm.phone=this.userInfo.phone;
      this.addressForm.gender=this.userInfo.gender;
    },

    submitAddressForm(){

      let arr = [];

      for (let i = 0; i < this.addressForm.addressCode.length; i++) {
        arr[i] = codeToText[this.addressForm.addressCode[i]];
      }

      const formData = {
        consignee: this.addressForm.consignee,
        phone: this.addressForm.phone,
        gender: this.addressForm.gender,
        label: this.addressForm.label,
        detail: this.addressForm.detail,
        provinceCode: this.addressForm.addressCode[0],
        provinceName: arr[0],
        cityCode: this.addressForm.addressCode[1],
        cityName: arr[1],
        districtCode: this.addressForm.addressCode[2],
        districtName: arr[2]
      };

      this.$refs.addressForm.validate((valid) => {
        if (valid) {
          axios.post("/user/address/add", formData).then((response) => {
            if (response.data.code === 0) {
              this.$message.error(response.data.msg);
            }else {
              this.$message.success("新增成功");
              //TODO 重新获取地址信息
            }
          }).catch((error) => {
            this.$message.error(error);
          })
        }else {
          console.log("error submit");
          return false;
        }
      })
    },

    resetAddressForm(){
      this.$refs.addressForm.resetFields();
    },

    /**
     * 获取地址信息
     */
    getAddressInfo(){
      axios.get("/user/address/list").then((response) => {
        if (response.data.code === 0) {
          this.$message.error(response.data.msg);
        }else {
          this.addresses=response.data.data;
        }
      }).catch((error) => {
        this.$message.error(error);
      })
    }
  }
}
</script>

<style scoped>
/*头像上传样式*/
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409EFF;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}

/*页面整体布局*/
.UserPage {
  background: linear-gradient(to bottom, #a1d2ff, #ffffff);
}
.page-container {
  display: flex;
  justify-content: center;
  align-items: center;
  width: 100%;
}

/*页面头部*/
.page-header {
  margin-top: 10px;
  width: 80%;
}

/*头像和问候语句的排版*/
.page-header-title{
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.greeting {
  display: flex;
  height: 50px;
  margin-left: 40px;
  font-size: 40px;
  color: #171717;
}

.user-tags{
  display: flex;
  height: 50px;
  margin-top: 30px;
  margin-left: 40px;
  font-size: 15px;
  color: #171717;
}

.button-group{
  margin-top: 60px;
  margin-left: auto;
}

/*页面主体*/
.page-content {
  display: flex;
  justify-content: center;
}

.page-content-container {
  display: flex;
  padding-top: 20px;
  padding-bottom: 20px;
  width: 80%;
}

.tabs-region {
  width: 70%;
}

.card-region {
  width: 30%;
  margin-left: 10px;
}

.border-card {
  height: 700px;
}

/*用户地址展示样式*/
.user-address {
  margin-top: 30px;
}

.address{
  display: flex;
  justify-content: space-between;
}

.address-title{
  display: flex;
}

.address-button{
  margin-left: auto;
}

/*底部按钮区域样式*/
.user-security{
  margin-top: 30px;
}
</style>


